﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;

using CloudSoft.Workflows;
using ERPStore.NewsLetters.Repositories;

namespace ERPStore.NewsLetters.Workflows.Activities
{

	public sealed class WriteTrackLog : CodeActivity
	{
		public InArgument<Models.TrackingKey> TrackingKey { get; set; }
		public InArgument<string> RawUrl { get; set; }
		public InArgument<string> IP { get; set; }
		public InArgument<string> DestinationUrl { get; set; }

		protected override void Execute(CodeActivityContext context)
		{
			var trackRepository = context.GetService<Services.TrackerService>();
			var newsLetterService = context.GetService<Services.NewsLettersService>();

			var trackingKey = context.GetValue(this.TrackingKey);
			var rawUrl = context.GetValue(this.RawUrl);
			var ip = context.GetValue(this.IP);
			var destinationUrl = context.GetValue(DestinationUrl);
			var emailSentResult = newsLetterService.GetLastEmailSentByRecipientId(trackingKey.EmailRecipientId);

			var creationDate = DateTime.Now;
			int? emailSentId = null;
			if (emailSentResult != null)
			{
				creationDate = emailSentResult.SentDate;
				emailSentId = emailSentResult.Id;
			}
			trackRepository.WriteTrack(trackingKey, creationDate, rawUrl, ip, destinationUrl, emailSentId);
			SendSignal(context, trackingKey, creationDate, rawUrl, ip, destinationUrl, emailSentId);
		}

		private void SendSignal(CodeActivityContext context, Models.TrackingKey tracking, DateTime creationDate, string rawurl, string ip, string destinationUrl, int? emailSentId)
		{
			var emailSentRepository = context.GetService<Services.NewsLettersService>();
			var emailSent = new Models.EmailSentResult();
			if (emailSentId.HasValue)
			{
				emailSent = emailSentRepository.GetEmailSentById(emailSentId.Value);
			}

			var track = new Models.Track();
			track.CreationDate = creationDate;
			track.EventDate = DateTime.Now;
			track.CampaingId = tracking.CampaignId;
			track.Email = tracking.Email;
			track.LinkName = tracking.LinkName;
			track.NewsLetterId = tracking.NewsLetterId;
			track.UserId = tracking.UserId;
			track.Ip = ip;
			track.Url = rawurl;
			track.EmailSent = emailSent;
			track.DestinationUrl = destinationUrl;

			var jsonSerializer = new Newtonsoft.Json.JsonSerializer();
			var sb = new StringBuilder();
			var textWriter = new System.IO.StringWriter(sb);
			var jsonWriter = new Newtonsoft.Json.JsonTextWriter(textWriter);
			jsonSerializer.Serialize(jsonWriter, track);

			var cnx = SignalR.GlobalHost.ConnectionManager.GetConnectionContext<Services.NewsLetterConnection>();
			cnx.Connection.Broadcast(sb.ToString());
		}
	}
}
